#!/usr/bin/env Python
#coding=utf-8

'''
server for east
v1 
    no tfserving
    gunicorn + flask
'''
from flask import Flask,request,jsonify
import traceback
import base64
from io import BytesIO
from eastserver import *
# from server.config import *
import numpy as np
import json
logging.basicConfig(filename='server_log/info.log', level=logging.DEBUG,format ='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

app = Flask(__name__)
eastServer = EASTSERVER()
logging.info("-----------------------east register-----------------------")
eastServer.register_mtp()



@app.route('/split', methods=['POST'])
def split():
    result = {}
    result["code"] = -1
    logging.info("-----------------------get http request-----------------------")
    try:
        data = request.get_data()
        j_data =  json.loads(data)
        pic = BytesIO()
        pic.write(base64.b64decode(j_data['imgbase64']))
        pic.seek(0)
        file_bytes = np.asarray(bytearray(pic.read()), dtype=np.uint8)
        img = cv2.imdecode(file_bytes, 1)
        split_box = eastServer.predictor(img)
        result["data"] = split_box
        # result["pic_pos"] = []
        # for item in split_box:
        #     result_temp = {}
        #     result_temp["x_min"] = item[0]
        #     result_temp["x_max"] = item[1]
        #     result_temp["y_min"] = item[2]
        #     result_temp["y_max"] = item[3]
        #     result["pic_pos"] += [result_temp]
        # # print result
        # # result_j = json.dumps(result)
        # # print "result_j:",result_j
        result["code"] = 0
        # result_json = jsonify(result)
        # logging.info("-----------------------http response-----------------------:%s"%result_json)
        return result
    except Exception as e:
        exstr = traceback.format_exc()
        logging.error(exstr)
        result["msg"] = exstr
    finally:
        return jsonify(result)
    

if __name__ == '__main__':
    app.run(debug=False,host='0.0.0.0',port=7000)
